"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import { Play, ExternalLink, ChevronLeft, ChevronRight } from "lucide-react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Button } from "@/components/ui/button"
import { SongCard } from "@/components/song-card"
import { AlbumCard } from "@/components/album-card"
import { MvCard } from "@/components/mv-card"
import type { Album, AlbumBase, Artist, Song, MV } from "@/types"
import { fetchAlbumsByArtistId, fetchArtistDetail, fetchMvsByArtistId, fetchSongsByArtistId } from "@/lib/api-client"

// 使用正确的播放器上下文
import { usePlayer } from "@/contexts/player-context"
import { useParams } from "next/navigation"

export default function ArtistPage() {
  const [artist, setArtist] = useState<Artist | null>(null)
  const [songs, setSongs] = useState<Song[]>([])
  const [albums, setAlbums] = useState<AlbumBase[]>([])
  const [mvs, setMvs] = useState<MV[]>([])
  const [loading, setLoading] = useState(true)
  const [tabLoading, setTabLoading] = useState(false)
  const { playQueue } = usePlayer()
  const [activeTab, setActiveTab] = useState("songs")
  const [showFullDescription, setShowFullDescription] = useState(false)
  const { id } = useParams()

  // 歌曲分页
  const [songsCurrentPage, setSongsCurrentPage] = useState(1)
  const [songsTotalPages, setSongsTotalPages] = useState(1)
  const [songsTotalCount, setSongsTotalCount] = useState(0)
  const songsPerPage = 10 // 每页显示10首歌曲

  // 专辑分页
  const [albumsCurrentPage, setAlbumsCurrentPage] = useState(1)
  const [albumsTotalPages, setAlbumsTotalPages] = useState(1)
  const [albumsTotalCount, setAlbumsTotalCount] = useState(0)
  const albumsPerPage = 10 // 每页显示10张专辑

  // MV分页
  const [mvsCurrentPage, setMvsCurrentPage] = useState(1)
  const [mvsTotalPages, setMvsTotalPages] = useState(1)
  const [mvsTotalCount, setMvsTotalCount] = useState(0)
  const mvsPerPage = 8 // 每页显示8个MV

  // 获取歌手详情
  useEffect(() => {
    const getArtistDetails = async () => {
      try {
        setLoading(true)
        const artistData = await fetchArtistDetail(id, localStorage.getItem("userId"))
        setArtist(artistData)
      } catch (error) {
        console.error("拉取歌手数据失败：:", error)
      } finally {
        setLoading(false)
      }
    }

    getArtistDetails()
  }, [id])

  // 歌曲分页控制
  const handleSongsPrevPage = () => {
    if (songsCurrentPage > 1) {
      setSongsCurrentPage(songsCurrentPage - 1)
    }
  }

  const handleSongsNextPage = () => {
    if (songsCurrentPage < songsTotalPages) {
      setSongsCurrentPage(songsCurrentPage + 1)
    }
  }

  // 专辑分页控制
  const handleAlbumsPrevPage = () => {
    if (albumsCurrentPage > 1) {
      setAlbumsCurrentPage(albumsCurrentPage - 1)
    }
  }

  const handleAlbumsNextPage = () => {
    if (albumsCurrentPage < albumsTotalPages) {
      setAlbumsCurrentPage(albumsCurrentPage + 1)
    }
  }

  // MV分页控制
  const handleMvsPrevPage = () => {
    if (mvsCurrentPage > 1) {
      setMvsCurrentPage(mvsCurrentPage - 1)
    }
  }

  const handleMvsNextPage = () => {
    if (mvsCurrentPage < mvsTotalPages) {
      setMvsCurrentPage(mvsCurrentPage + 1)
    }
  }

  // 获取标签页数据
  useEffect(() => {
    const fetchTabData = async () => {
      if (!artist) return

      setTabLoading(true)
      try {
        if (activeTab === "songs") {
          const songsData = await fetchSongsByArtistId(id, localStorage.getItem("userId"), {
            page: songsCurrentPage,
            limit: songsPerPage,
          })
          setSongs(songsData.items || [])
          setSongsTotalCount(songsData.total || 0)
          setSongsTotalPages(Math.ceil((songsData.total || 0) / songsPerPage))
        } else if (activeTab === "albums") {
          const albumsData = await fetchAlbumsByArtistId(id, localStorage.getItem("userId"), {
            page: albumsCurrentPage,
            limit: albumsPerPage,
          })
          setAlbums(albumsData.items || [])
          setAlbumsTotalCount(albumsData.total || 0)
          setAlbumsTotalPages(Math.ceil((albumsData.total || 0) / albumsPerPage))
        } else if (activeTab === "mv") {
          const mvsData = await fetchMvsByArtistId(id, localStorage.getItem("userId"), {
            page: mvsCurrentPage,
            limit: mvsPerPage,
          })
          setMvs(mvsData.items || [])
          setMvsTotalCount(mvsData.total || 0)
          setMvsTotalPages(Math.ceil((mvsData.total || 0) / mvsPerPage))
        }
      } catch (error) {
        console.error(`获取${activeTab}数据失败:`, error)
      } finally {
        setTabLoading(false)
      }
    }

    fetchTabData()
  }, [
    activeTab,
    artist,
    id,
    songsCurrentPage,
    albumsCurrentPage,
    mvsCurrentPage,
    songsPerPage,
    albumsPerPage,
    mvsPerPage,
  ])

  // 切换标签时重置对应标签的页码
  useEffect(() => {
    if (activeTab === "songs") {
      setSongsCurrentPage(1)
    } else if (activeTab === "albums") {
      setAlbumsCurrentPage(1)
    } else if (activeTab === "mv") {
      setMvsCurrentPage(1)
    }
  }, [activeTab])

  const handlePlayAll = () => {
    if (songs.length > 0) {
      // 使用播放器上下文中的方法来播放队列
      playQueue(songs)
    }
  }

  if (loading) {
    return (
        <div className="flex justify-center items-center min-h-screen">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
        </div>
    )
  }

  if (!artist) {
    return (
        <div className="flex justify-center items-center min-h-screen">
          <p className="text-lg">未找到歌手信息</p>
        </div>
    )
  }

  // 截断描述文本，只显示前100个字符
  const truncatedDescription =
      artist.description && artist.description.length > 100
          ? `${artist.description.substring(0, 100)}...`
          : artist.description

  const displayDescription = showFullDescription ? artist.description : truncatedDescription

  return (
      <div className="container mx-auto px-4 py-6">
        <div className="flex flex-col md:flex-row gap-6 mb-8">
          {/* 左侧：艺术家头像 */}
          <div className="md:w-40">
            <div className="relative w-40 h-40 rounded-full overflow-hidden bg-gray-200 mx-auto">
              <Image
                  src={artist.avatar || "/placeholder.svg?height=160&width=160"}
                  alt={artist.name}
                  fill
                  className="object-cover"
              />
            </div>
          </div>

          {/* 右侧：艺术家信息和简介 */}
          <div className="flex-1 flex flex-col">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-4">
              <div>
                <h1 className="text-3xl font-bold">{artist.name}</h1>
              </div>

              <div className="flex gap-4">
                {activeTab === "songs" && songs.length > 0 && (
                    <Button onClick={handlePlayAll} className="flex items-center gap-2 bg-primary text-primary-foreground">
                      <Play size={16} /> 播放全部
                    </Button>
                )}
              </div>
            </div>

            {/* 艺术家简介 */}
            {artist.description && (
                <div className="bg-gray-800/30 p-4 rounded-lg mb-6">
                  <p className="text-gray-300 text-sm leading-relaxed">{displayDescription}</p>
                  {artist.description.length > 100 && (
                      <button
                          onClick={() => setShowFullDescription(!showFullDescription)}
                          className="text-primary text-sm mt-2 flex items-center hover:underline"
                      >
                        {showFullDescription ? "收起" : "查看更多"}
                        <ExternalLink size={14} className="ml-1" />
                      </button>
                  )}
                </div>
            )}
          </div>
        </div>

        <Tabs defaultValue="songs" className="w-full" onValueChange={setActiveTab}>
          <TabsList className="mb-6">
            <TabsTrigger value="songs">歌曲</TabsTrigger>
            <TabsTrigger value="albums">专辑</TabsTrigger>
            <TabsTrigger value="mv">MV</TabsTrigger>
          </TabsList>

          {tabLoading ? (
              <div className="flex justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
              </div>
          ) : (
              <>
                {/* 歌曲标签内容 */}
                <TabsContent value="songs">
                  <div className="relative">
                    <div className="space-y-4 mb-6">
                      {songs.length > 0 ? (
                          songs.map((song, index) => (
                              <SongCard
                                  key={song.id}
                                  song={song}
                                  index={index + 1 + (songsCurrentPage - 1) * songsPerPage}
                                  showAlbum={true}
                                  onSongUpdated={(updatedSong: Song) => {
                                    setSongs((prev) => prev.map((s) => (s.id === updatedSong.id ? updatedSong : s)))
                                  }}
                              />
                          ))
                      ) : (
                          <p className="text-center py-8 text-gray-500">暂无歌曲</p>
                      )}
                    </div>

                    {/* 歌曲分页控制 */}
                    {songs.length > 0 && songsTotalPages > 1 && (
                        <div className="flex justify-center items-center mt-6 space-x-4">
                          <Button
                              variant="outline"
                              size="sm"
                              onClick={handleSongsPrevPage}
                              disabled={songsCurrentPage === 1}
                              className="flex items-center gap-1"
                          >
                            <ChevronLeft className="h-4 w-4" />
                            上一页
                          </Button>
                          <span className="text-sm">
                      第 {songsCurrentPage} 页，共 {songsTotalPages} 页
                    </span>
                          <Button
                              variant="outline"
                              size="sm"
                              onClick={handleSongsNextPage}
                              disabled={songsCurrentPage === songsTotalPages}
                              className="flex items-center gap-1"
                          >
                            下一页
                            <ChevronRight className="h-4 w-4" />
                          </Button>
                        </div>
                    )}
                  </div>
                </TabsContent>

                {/* 专辑标签内容 */}
                <TabsContent value="albums">
                  <div className="relative">
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-6">
                      {albums.length > 0 ? (
                          albums.map((album) => (
                              <AlbumCard
                                  key={album.id}
                                  album={album}
                                  onAlbumUpdated={(updatedAlbum: Album) => {
                                    setAlbums((prev) => prev.map((a) => (a.id === updatedAlbum.id ? updatedAlbum : a)))
                                  }}
                              />
                          ))
                      ) : (
                          <p className="text-center py-8 text-gray-500 w-full col-span-full">暂无专辑</p>
                      )}
                    </div>

                    {/* 专辑分页控制 */}
                    {albums.length > 0 && albumsTotalPages > 1 && (
                        <div className="flex justify-center items-center mt-6 space-x-4">
                          <Button
                              variant="outline"
                              size="sm"
                              onClick={handleAlbumsPrevPage}
                              disabled={albumsCurrentPage === 1}
                              className="flex items-center gap-1"
                          >
                            <ChevronLeft className="h-4 w-4" />
                            上一页
                          </Button>
                          <span className="text-sm">
                      第 {albumsCurrentPage} 页，共 {albumsTotalPages} 页
                    </span>
                          <Button
                              variant="outline"
                              size="sm"
                              onClick={handleAlbumsNextPage}
                              disabled={albumsCurrentPage === albumsTotalPages}
                              className="flex items-center gap-1"
                          >
                            下一页
                            <ChevronRight className="h-4 w-4" />
                          </Button>
                        </div>
                    )}
                  </div>
                </TabsContent>

                {/* MV标签内容 */}
                <TabsContent value="mv">
                  <div className="relative">
                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mb-6">
                      {mvs.length > 0 ? (
                          mvs.map((mv) => <MvCard key={mv.id} mv={mv} />)
                      ) : (
                          <p className="text-center py-8 text-gray-500 w-full col-span-full">暂无MV内容</p>
                      )}
                    </div>

                    {/* MV分页控制 */}
                    {mvs.length > 0 && mvsTotalPages > 1 && (
                        <div className="flex justify-center items-center mt-6 space-x-4">
                          <Button
                              variant="outline"
                              size="sm"
                              onClick={handleMvsPrevPage}
                              disabled={mvsCurrentPage === 1}
                              className="flex items-center gap-1"
                          >
                            <ChevronLeft className="h-4 w-4" />
                            上一页
                          </Button>
                          <span className="text-sm">
                      第 {mvsCurrentPage} 页，共 {mvsTotalPages} 页
                    </span>
                          <Button
                              variant="outline"
                              size="sm"
                              onClick={handleMvsNextPage}
                              disabled={mvsCurrentPage === mvsTotalPages}
                              className="flex items-center gap-1"
                          >
                            下一页
                            <ChevronRight className="h-4 w-4" />
                          </Button>
                        </div>
                    )}
                  </div>
                </TabsContent>
              </>
          )}
        </Tabs>
      </div>
  )
}

